/*
 * Project Name spring-boot-tools
 * File Name MPMessageDecoder
 * Package Name com.huxiaosu.tools.cmpp.codec
 * Create Time 2024/4/18
 * Create by name：liujie
 */
package com.huxiaosu.tools.cmpp.codec;

import com.huxiaosu.tools.cmpp.action.MessageActionPool;
import com.huxiaosu.tools.cmpp.enums.CommandId;
import com.huxiaosu.tools.cmpp.model.BaseMessage;
import com.huxiaosu.tools.cmpp.model.MessageHeader;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import java.net.InetSocketAddress;

/**
 * 自定义解码器
 *
 * @author liujie
 * @date 2024/4/18 23:36
 */
@SuppressWarnings("AlibabaUndefineMagicConstant")
@Slf4j
public class MPMessageDecoder extends CumulativeProtocolDecoder {

    private String charset;

    public MPMessageDecoder() {
        this.setCharset("UTF-8");
    }

    public MPMessageDecoder(String charset) {
        this.setCharset(charset);
    }

    @Override
    protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {

        if (in.remaining() < 4) {
            return false;
        }
        in.mark();
        BaseMessage message = new BaseMessage();
        InetSocketAddress socketAddress = (InetSocketAddress) session.getRemoteAddress();
        message.setClientIp(socketAddress.getAddress().getHostAddress());

        Integer totalLength = in.getInt();
        log.info(" <totalLength={} >", totalLength);
        message.setTotalLength(totalLength);
        int commandId = in.getInt();
        log.info("< commandId={} >", CommandId.getById(commandId).name());
        CommandId command = CommandId.getById(commandId);
        message.setCommandId(command);
        Integer sequenceId = in.getInt();
        log.info("< sequenceId={} >", sequenceId);
        message.setSequenceId(sequenceId);

        MessageHeader actionMessageHeader = MessageActionPool.getInstance().getAction(command).readMessage(in);
        message.setMessageHeader(actionMessageHeader);
        out.write(message);
        in.mark();

        if (in.remaining() > 0) {
            return true;
        }

        return false;
    }

    /**
     * @return the charset
     */
    public String getCharset() {
        return charset;
    }

    /**
     * @param charset the charset to set
     */
    public void setCharset(String charset) {
        this.charset = charset;
    }

}
